package com.niit.chat.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.niit.chat.entity.Message;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 消息Mapper接口
 */
@Mapper
public interface MessageMapper extends BaseMapper<Message> {
    
    /**
     * 获取两个用户之间的聊天记录
     * @param userId 用户ID
     * @param targetUserId 目标用户ID
     * @param offset 偏移量
     * @param limit 限制数量
     * @return 消息列表
     */
    @Select("SELECT * FROM tb_message " +
            "WHERE (sender_id = #{userId} AND receiver_id = #{targetUserId}) " +
            "OR (sender_id = #{targetUserId} AND receiver_id = #{userId}) " +
            "AND is_deleted = 0 " +
            "ORDER BY send_date DESC " +
            "LIMIT #{offset}, #{limit}")
    List<Message> getChatHistory(@Param("userId") Long userId, 
                                @Param("targetUserId") Long targetUserId,
                                @Param("offset") Integer offset,
                                @Param("limit") Integer limit);
    
    /**
     * 获取用户的未读消息数量
     * @param userId 用户ID
     * @return 未读消息数量
     */
    @Select("SELECT COUNT(*) FROM tb_message " +
            "WHERE receiver_id = #{userId} " +
            "AND is_read = 0 " +
            "AND is_deleted = 0")
    Integer getUnreadCount(@Param("userId") Long userId);
    
    /**
     * 获取用户的所有会话列表
     * @param userId 用户ID
     * @return 会话列表
     */
    @Select("SELECT DISTINCT " +
            "CASE " +
            "  WHEN sender_id = #{userId} THEN receiver_id " +
            "  ELSE sender_id " +
            "END as user_id, " +
            "MAX(send_date) as last_message_time " +
            "FROM tb_message " +
            "WHERE (sender_id = #{userId} OR receiver_id = #{userId}) " +
            "AND is_deleted = 0 " +
            "GROUP BY user_id " +
            "ORDER BY last_message_time DESC")
    List<Message> getSessionList(@Param("userId") Long userId);
} 